<template>
	<view class="pro-body">
	
		<view class="body" >
			<view class="top-container">
				<uni-list :border="false" >
					<uni-list-item :border="false" title="单据编号"  :rightText="header.fbillNo" />
					<uni-list-item :border="false" title="生产订单单号"  :rightText="header.fbillnomo" />
					<uni-list-item :border="false" title="创建人"  :rightText="header.fcreateuser" />
					<uni-list-item :border="false" title="入库日期">
						<template v-slot:footer >
							<uni-datetime-picker type="line" v-model="header.fdate" @change="onInStockTimeChange"
								placeholder="请选择入库时间">
							</uni-datetime-picker>
						</template>
					</uni-list-item>
				</uni-list>
			</view>
			<template v-if="detail && detail.length > 0">
				<view class="" v-for="(item,index) in detail" :key = "index">
					   
					<view class="panel">
						
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">物料编码：</view>
									<view class="panel_content_row_item_value">{{ item.fmaterialnumber }}</view>
								</view>
							</view>
						</view>
								
					    <view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">名称：</view>
									<view class="panel_content_row_item_value">{{ item.fmaterialname }}</view>
								</view>
							</view>
						</view>
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">件号：</view>
									<view class="panel_content_row_item_value">{{ item.fspecification }}</view>
								</view>
								<!-- 暂时没有材质，用单位代替 -->
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">单位：</view>
									<view class="panel_content_row_item_value">{{ item.funitname }}</view>
								</view>
							</view>
						</view>
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">应收数量：</view>
									<view class="panel_content_row_item_value">{{ item.fmustqty }}</view>
								</view>
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">实收数量：</view>
									<view class="panel_content_row_item_value">{{ item.frealqty }}</view>
								</view>
							</view>
						</view>
						
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">入库仓库：</view>
									<view class="sechoice">
										<uni-data-select v-model="item.fstocknumber" :localdata="item.stockList"
										 @change="change(item.fstocknumber,item)"   
										placeholder="请选择仓库"></uni-data-select>
									</view>
								</view>
								
							</view>
						</view>
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item" v-if="item.isLocation">
									<view class="panel_content_row_item_title">入库仓位：</view>
									<view class="panel_content_row_item_value">
										<input v-model="item.locationNo" placeholder="请输入仓位"
										placeholder-class="input_placeholder"
										style="width: 100px;"
										/>
									</view>
								</view>
							</view>
						</view>
						
						<view class="flex-list-btn" >
							<view  class="flex-list-btn-item" v-if="item.isLocation"
								@click="scanOrderDe(item)">
								扫描仓位
							</view>
							<!-- 打印按钮 -->
							  <view class="flex-list-btn-item print" @click="handlePrint(item)">
							    打印
							  </view>
						</view>
					</view>
				</view>

			</template>
			
		</view>	
		<!--  底部按钮  -->
		<view class="footerPanel">
			<view class="footerPanel_body">
				<button @click="auditPrdIn()" class="footerBtn save" :disabled="butClick"><i
						class="iconfont icon-duihao btn_icon" ></i>审核
				</button>
				
			</view>
		</view>
		<!-- 全局遮罩：在 butClick 为 true 时显示，阻止所有交互，显示转圈提示 -->
		<view v-if="butClick" class="global-mask">
		  <view class="loader-box">
		    <view class="loader"></view>
		    <view class="loader-text">审核中，请稍候...</view>
		  </view>
		</view>
		<!-- 扫描托盘 -->
		<tray-popup ref="trayPopupRef" @success="trayScanningScuess"></tray-popup>
</view>
</template>

<script>
	import uniTransition from 'uni_modules/uni-transition/components/uni-transition/uni-transition.vue';
	import trayPopup from '../../components/popup/trayPopup.vue'
	import {getProInstosckDetailKu,
	checkStock,
	auditPrdIn,
	getLocation,
	createTrayPda,
	getSerial
	} from '@/utils/api.js'
	import {printContect,
		printQRCode,
		printData,
		safePrint,
		printVerticalLabel,
		printTextAndQRCode} from '@/utils/print.js'
	export default {
		components: {
			trayPopup
		},
		data(){
			return{
				billNo: '',
				loading: true,
				header:{},
				detail:[],
				// isLocation:false,
				materialList : [],
				butClick : false,
				selectRange : [],
				currentItem : null,
				inStockTime: '',
				trayNo : ''//托盘号
			}
	},
	methods:{
		formatDateTime(date) {
			const y = date.getFullYear();
			const m = String(date.getMonth() + 1).padStart(2, '0');
			const d = String(date.getDate()).padStart(2, '0');
			const h = String(date.getHours()).padStart(2, '0');
			const min = String(date.getMinutes()).padStart(2, '0');
			const s = String(date.getSeconds()).padStart(2, '0');
			return `${y}-${m}-${d} ${h}:${min}:${s}`;
		},
		getTodayDateTime() {
			return this.formatDateTime(new Date());
		},
		onInStockTimeChange(val) {
			// 有些端返回时间戳或 ISO 格式，这里统一转成 yyyy-MM-dd HH:mm:ss
			if (typeof val === 'string') {
				this.inStockTime = val.length > 19 ? val.slice(0, 19).replace('T', ' ') : val
			} else {
				this.inStockTime = this.formatDateTime(new Date(val))
			}
		},
		createTrayPda(item){
		
			let map ={
				itemnumber : item.fmaterialnumber,
				fqty : item.frealqty,
				flot : item.flot,
				instockId : item.id
			}
		
			createTrayPda(map).then(res => {
				if (res.data.status === 200){
					this.trayNo = res.data.msg
				}
			})
		},
		//打印
		handlePrint(item){
		
			//获取生产日期和涂成号
			getSerial({'trayNo':this.header.trayno,'fspecification':item.fspecification}).then(res =>{

				let values = {
					'件号': item.fspecification,
					'数量' : item.frealqty,
					'入库':this.inStockTime.slice(0,10)
				};
				safePrint()//校验打印机是否连接
				printTextAndQRCode(values,this.header.trayno)
				
			
			})
			
		},
		//填写合格数量
		handleQuality(e){
			if (e.realQty <= e.mustQty ){
				const v = e.realQty
				const zero = "(/^\D*(\d*(?:\.\d{0,2})?).*$/g,'$1')"
				let final = 0
				if (!v) {
				  final = 0
				} else {
				  final = v.toString().replace(zero, (v) => {
					return 0
				  })
						
				  if (final.split('')[0] * 1 === 0) {
					final = final.slice(1) - 0 || 0
				  }
				}
				this.$nextTick(() => {
				 e.realQty = final.toString() || '0'
				})
				
			} else{
				uni.showToast({
					title:'实收数量不能大于应收数量',
					icon:'none'
				})
				e.realQty = 0
			}
			
		},
		//扫描仓位，扫描成功后修改下拉框中仓位信息
		scanOrderDe(item) {
			this.currentItem = item
			this.$refs.trayPopupRef.open()
			
		},
		
		//修改仓库后重新校验仓库有没有启用仓位
		change(e,item){
			for(let i =0;i < item.stockList.length;i++){
				if (item.stockList[i].value == e){
					// this.$set(item,'fstockname',item.stockList[i].text)
					item.fstockname = item.stockList[i].text
				}
			}

			this.checkStock(e,item)
			//将仓位赋值为空
		
		},
		//扫码成功后返回
		trayScanningScuess(e){
			if (!this.detail[0].locationList.includes(e)){
				uni.showToast({
					title:'仓位错误请重试',
					icon:'error'
				})
				return;
			}
			
			  //this.currentItem.locationNo = e;
		const index = this.detail.findIndex(i => i.id === this.currentItem.id)
		  if (index !== -1) {
		    this.detail.splice(index, 1, { ...this.currentItem, locationNo: e })
		  }
			
		},
		//检查当前仓库是否启用仓位
		checkStock(stockNo,item){
			checkStock({stockNo : stockNo}).then(res =>{
				item.isLocation = res.data.data
				//如果仓库启用仓位的话查询仓位信息
				if (item.isLocation){
					this.getLocation(stockNo,item)
				}
			})
		},
		//获取仓位信息
		getLocation(stockNo,item){
			getLocation({stockNo:stockNo}).then(res =>{
			
				item.locationList = res.data.data
			})
		},
		//审核采购入库单
		auditPrdIn(){
			let self = this;

			uni.showModal({
				title:'提示',
				content:'确认审核',
				success(res) {
					if (res.confirm){
						self.butClick = true; // 禁止其他操作
						uni.showLoading({
							title: "审核中...",
							mask: true
						});
						//没启用的话可以直接审核
						auditPrdIn({billNo : self.header.fbillNo,
						locatioNo : self.locationNo,
						dataList : self.detail,
						inStockTime : self.inStockTime}).then(result => {
							uni.hideLoading();
							self.butClick = false;
						if (result.data.data){
							uni.showToast({
								title:'审核成功',
								icon:'none'
							})
						}
						
						setTimeout(() =>{
							uni.navigateBack({
								delta:1,
								success() {
									uni.$emit('update',{msg:'页面刷新'});
								}
							})
						},2000)
						}).catch(err => {
		                    // 接口异常恢复按钮和 loading
		                    uni.hideLoading();
		                    self.butClick = false;
		
		                    // uni.showModal({
		                    // 	title:'提示',
		                    // 	content:'接口异常,请联系谭工'
		                    // })
		                    
		                });
					
					}
				}
			})
		},
		
		// 获取详情数据
		initData(){
			getProInstosckDetailKu({billNo :this.billNo }).then(res => {
				this.header = res.data.data.data
				this.detail = res.data.data.dataList
				this.inStockTime = this.header.fdate || this.getTodayDateTime()
				this.detail.forEach((item,index ) => {
					item.locationNo = '998'
				})
			
			})
		
		
		}
	},
	onLoad(e){
		this.billNo = e.billNo
		// 获取详情数据
		this.initData()
		
	},
	mounted() {
		
		
	}
}
</script>

<style lang="scss" >
	
	@import "../../static/css/common";

	 ::v-deep .uni-datetime-picker-popup {
			height: 32rpx;
			
		}
	/* 调整列表项左右文字大小 */
	::v-deep .uni-list-item__content-title {
	    font-size: 20px !important;  /* 左侧标题字体大小 */
		padding-left: 5px;
	}
	::v-deep .uni-list-item__extra-text {
	    font-size: 22px !important;  /* 右侧内容字体大小 */
		padding-right: 5px;
		 color: #333;
	}
	/* 调整行间距 */
	::v-deep .uni-list-item__container {
	    padding: 3px 0 !important;   /* 减小上下内边距 */
	    min-height: 10px !important; /* 减小最小高度 */
	}
	/* 新增日期样式 */
	::v-deep .custom-date {
	    font-size: 22px !important;  /* 与右侧文本相同大小 */
	    color: #333 !important;      /* 与右侧文本相同颜色 */
	    padding-right: 5px !important; /* 与右侧文本相同内边距 */
	}

.panel {
  background: #fbffe2;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}
 
/* 调整标题样式 */
.panel_content_row_item_title {
    font-size: 17px !important;  /* 调大字体 */
    color: #000000 !important;   /* 纯黑字体 */
    flex-shrink: 0;             /* 防止压缩 */
}
/* 调整标题样式 */
.panel_content_row_item_value {
  flex: 1;
  font-size: 17px !important; /* 数值特别放大 */
  color: #333 !important;
}
	
	.sechoice {//调整下拉列表框	    
	    height: 100px;
	    display: flex;
	    align-items: center;
	    justify-content: center;
		padding: 15px;
	
	}

/* 底部按钮 - 修改布局 */
	.footerPanel {
	  height: 60px;
	  .footerPanel_body {
	    display: flex;
	    justify-content: space-between; /* 左右分布按钮 */
	    width: 100%;
	    padding: 0 10px;
	    box-sizing: border-box;
	    
	    .footerBtn {
	      height: 55px;
	      min-width: 115px;
	      display: flex;
	      line-height: 1;
	      font-size: 20px; /* 适当增大字体 */
	      border-radius: 8px;
	      align-items: center;
	      justify-content: center;
	      box-shadow: 0 2px 5px rgba(0,0,0,0.2);
	      color: #fff;
	      border: none;
	      // margin: 0 10px;
	    }
	  }
	}
	/* 全局遮罩 (覆盖整个页面，挡住所有点击) */
	.global-mask {
	  position: fixed;
	  left: 0;
	  top: 0;
	  right: 0;
	  bottom: 0;
	  z-index: 9999;
	  background: rgba(0,0,0,0.45);
	  display: flex;
	  align-items: center;
	  justify-content: center;
	}
	
	/* loader 容器 */
	.loader-box {
	  display: flex;
	  flex-direction: column;
	  align-items: center;
	  justify-content: center;
	  padding: 20px 30px;
	  background: rgba(255,255,255,0.95);
	  border-radius: 8px;
	}
	
	/* CSS 简易转圈 */
	.loader {
	  width: 44px;
	  height: 44px;
	  border-radius: 50%;
	  border: 4px solid rgba(0,0,0,0.1);
	  border-top-color: #ffffff;
	  border-right-color: #ffffff;
	  animation: spin 1s linear infinite;
	  margin-bottom: 8px;
	}
	
	.loader-text {
	  font-size: 14px;
	  color: #333;
	}
	
	/* 动画 */
	@keyframes spin {
	  from { transform: rotate(0deg); }
	  to { transform: rotate(360deg); }
	}
	
</style>